<template>
  <d2-container>
  <section class="">
    <el-row style="padding:10px 20px 16px; ">
      <el-col :span="7">
        <span style="font-size: 14px;margin-right: 5px" class="theme-front-color">采集器名称</span>
        <el-select v-model="select_colt" placeholder="请选择采集器" size="small"  filterable style="width:60%"  @change="show_meters(true)">
          <el-option v-for="item in coltorsList" :label="item.equiName" :value="item.equiCode" :key="item.equiCode"></el-option>
        </el-select>
      </el-col>
      <el-col :span="7">
        <span style="font-size: 14px;margin-right: 5px" class="theme-front-color">采集数据类型</span>
        <el-select v-model="select_type"  filterable style="width:60%" size="small" @change="show_meters(false)">
          <el-option v-for="item in meterTypeList" :label="item.paramValue"
                     :value="item.paramKey" :key="item.paramKey"></el-option>
        </el-select>
      </el-col>
      <el-col :span="7">
        <span style="font-size: 14px;margin-right: 5px" class="theme-front-color">监测对象</span>
        <el-select v-model="select_meter"  filterable style="width:60%" size="small" >
          <el-option v-for="item in meters_list" :label="item.deviceName" :value="item.meterCode" :key="item.meterCode"></el-option>
        </el-select>
      </el-col>
      <el-col :span="3"  style="text-align: left">
        <el-button @click="get_sample(true)" type="info" size="small" style="width: 80px;border-radius: 0;background: #4d87df; border: 1px solid #4d87df;border-radius: 5px">查询</el-button>
      </el-col>
    </el-row>
    <el-row style="padding:0 20px 0">
      <el-row style="background:rgba(0,0,0,.1);padding:10px 20px; border-radius: 10px ">
        <el-row>
          <el-col :span="24">
            <el-radio-group v-model="model_type" size="small" @change="get_sample(true)">
              <el-radio-button v-for="param in  meterTypeParamValueList" :label="param.collectType" :key="param.collectType">{{param.collectName}}
              </el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="24"></el-col>
          <el-col :span="24"></el-col>
        </el-row>
      </el-row>
    </el-row>

    <el-row style="" v-loading="isLoading" element-loading-text="加载中..." >
      <div id="myChart" :style="{width: '100%', height: chartHeight+'px'}" >
      </div>
    </el-row>
    <!--<el-row>-->
    <!--<div id="myChart" :style="{width: '1000px', height: '500px'}"></div>-->
    <!--</el-row>-->
  </section>
  </d2-container>
</template>

<script>

  import commondef from '@/utils/common'
  // 引入基本模板
  import * as echarts from 'echarts'
  import * as Util from "@/utils";

  export default {
    data() {
      return {
        pickerOptions2: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          }
        },
        model_type: '电流',
        select_colt: '',
        select_type: '',
        select_meter: '',
        select_dy: '',
        coltorsList: [],
        customer_id: this.$store.state.customer_id,
        energy_type: this.$store.state.customer_energy_type,
        meterTypeList: [],
        meters_list: [],
        show_meter_select: true,
        time_by_my: '',
        start_time: new Date().format('yyyy-MM-dd') + ' 00:00:00',
        end_time: new Date().format('yyyy-MM-dd') + ' 23:59:59',
        type_date: [],
        echart_data_list: [],
        echart_data_time:[],
        isLoading: false,
        meterTypeParamValueList:[],
        unit:'',
        timeOut:null,

      }
    },
    computed: {
      chartHeight(){
        return Util.getClientHeight() - 300;
      }
    },
    methods: {
      get_sample (type) {  // 获取该位号在特定时间内的值
        if (this.select_meter === '') {
          this.$message.info('请选择监测对象')
        } else {
          //往前24小时的数据
          if(type){
            this.start_time = (new Date(new Date().getTime()-(24*3600*1000)).format('yyyy-MM-dd hh:mm:ss'))
          }
          this.end_time = (new Date().format('yyyy-MM-dd hh:mm:ss'))
          var para = {
            meterparas: [this.select_meter],
            begin: this.start_time,
            end: this.end_time,
            page_no: 1,
            energytype:this.model_type,
            page_size: 5000,
            customerId: this.$util.cookies.get("customer_id")
          }
          if(type){
             this.isLoading = true;
          }
          this.$api.okhttp({
            url: this.$http.adornUrl('/eda/datavincent.raw.get_samples_begin_end'),
            method: 'post',
            data: this.$http.adornParams(para)
          }).then(res => {
            if (res.code === 0) {
              if(res.data.samples&&res.data.samples.length>0){
                 this.get_serise(res.data.samples,type) //  进行数据处理
              }
              this.timeOut = setTimeout(()=>{ this.get_sample(false); },10*60*1000);
            } else {
              this.$message.info('当日数据错误，请联系管理员')
            }
            if(type){
              this.isLoading = false;
            }
          })
        }
      },
      // 电力的选择
      show_meters (type) {  //  对筛选出进行变化
        if (this.select_colt !== '' && this.select_type !== '') {
          this.show_meter_select = false
          this.getMetersCode(true)
        } else {
          this.show_meter_select = true
        }
        this.querySubitem(type);
      },
      getMetersCode (type) {  // 获取位号
        // console.log('1111')
        this.meters_list = []
        this.select_meter=''
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecsmeterinfo/getInfoByEquicode/'+this.select_colt),
          method: 'get',
          params: this.$http.adornParams({
            'projectId': this.$util.cookies.get("cuuren_projectId"),
            "customerId":this.$util.cookies.get('customer_id'),
            "meterType":this.select_type
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.meters_list = data.data;
            if(data.data.length>0){
              this.select_meter = data.data[0].meterCode;
            }
            this.querySubitem(true);
          }
        });


      },
      querySubitem(type){
        //查询子分类
        this.queryCollectType(this.select_type,'0',data=>{
          if (data && data.code === 0) {
            this.meterTypeParamValueList = data.page.list
            //默认参数选择
            this.model_type=this.meterTypeParamValueList.length?this.meterTypeParamValueList[0].collectType:''
            this.unit =  this.meterTypeParamValueList.length>0?
              this.meterTypeParamValueList.find(item=>item.collectType==this.model_type).collectUnit:
              this.meterTypeList.find(item=>this.select_type==item.paramKey).paramExt;
            if(type){
              this.get_sample(true);
            }
          } else {
            this.meterTypeParamValueList = [];
            this.unit =  this.meterTypeParamValueList.length>0?
            this.meterTypeParamValueList.find(item=>item.collectType==this.model_type).collectUnit:
            this.meterTypeList.find(item=>this.select_type==item.paramKey).paramExt;
        }
        });
      },
      /**
       * 获取采集分项
       */
      queryCollectType(type,paramValue,callback) {
        let params = {
          'meterType': type ,
          'state': '1' ,
          'cumulativeType':paramValue,
          "customerId":this.$util.cookies.get('customer_id'),
          'page': 1,
          'limit': 10000,
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },

      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{...paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      get_serise (data,type) {  //  进行数据重组，组成echar需要的数
        if(type){
          this.echart_data_list = [];
          this.echart_data_time = [];
        }
        else{
          if(this.echart_data_list.length>0){
            if(this.echart_data_list.length>data.length){
              this.echart_data_list.splice(0,data.length);
              this.echart_data_time.splice(0,data.length);
            }
            else{
              this.echart_data_lis= [];
              this.echart_data_time = [];
            }
          }

        }
        this.start_time = new Date(new Date(data[data.length-1].CollectTime).getTime()+1*1000).format("yyyy-MM-dd hh:mm:ss");
        for (let i = 0; i < data.length; i++) {
          this.echart_data_time.push(data[i].CollectTime);  //x轴数据
          this.echart_data_list.push(data[i].Params[this.model_type].OVal);
        }
        this.initEcharts(type);
      },
      getColt () { //  获取采集器
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecscollectequi/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 100000,
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.coltorsList = data.page.list
            this.select_colt = data.page.list[0].equiCode
            this.getMetersCode(true)
          } else {
            this.coltorsList = []
          }
        })
      },
      getItme() {   // 获取能源类型
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams({
            'code': 'METER_TYPE' ,
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.meterTypeList = data.page
            this.select_type = data.page[0].paramKey;
            this.unit = data.page[0].paramExt;
            this.getColt(true);
          } else {
            this.meterTypeList = []
          }
        });
      },
      initEcharts (flag) {   // 显示ecahars
        let myChart = echarts.init(document.getElementById('myChart'))
        if(flag){
          myChart.clear()
        }
        let option = {
          color: ['#FFCC00', '#00CC33', '#D05454', '#4C7EDF'],
          animation: true,
          legend: {
            data: this.meterTypeParamValueList.find(ele=>ele.collectType==this.model_type).collectName,
            right: 60,
            top: 25,
            borderRadius: 5
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          grid:{
              x:50,
              y:25,
              x2:55,
              y2:25,
              top:60,
          },
          xAxis: {
            type: 'category',
            data: this.echart_data_time
          },
          yAxis: {
            name: '单位:'+this.unit,
            type: 'value',
            min: function (value) {
              return value.min
            },
            splitLine: {
              show: true
            },
            axisLabel: {
              formatter: function (value) {
                if (value > 10000) {
                  value = (value / 1000).toFixed(1) + 'k'
                }
                return value
              }
            }
          },
          dataZoom: [{
            startValue: this.echart_data_time[0]
          }, {
            type: 'inside'
          }],
          series:{
            name: this.meterTypeParamValueList.find(ele=>ele.collectType==this.model_type).collectName,
            type: 'line',
            lineStyle: {
              normal: {
                width: 3
              }
            },
            smooth: 1,
            formatter: '{a}{c}',
            data:this.echart_data_list,
          }
        }
        myChart.setOption(option)
      }
    },
    created() {
        this.getItme()
    },
    destroyed(){
      if(this.timeOut){
        clearTimeout(this.timeOut);
      }
    },
    watch:{
      model_type:function(newValue,oldValue){
        this.unit =  this.meterTypeParamValueList.length>0?
        this.meterTypeParamValueList.find(item=>item.collectType==this.model_type).collectUnit:
        this.meterTypeList.find(item=>this.select_type==item.paramKey).paramExt;
      }
    }
  }
</script>
<style scoped lang="scss">
  @import "../../assets/scss/_variables";
  .el-radio-button:first-child .el-radio-button__inner {
    border-radius: 4px;
  }

  .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 4px;
    margin-right: 0;
  }
  .el-radio-button {
    margin-top: 8px;
    /*border-bottom: 1px solid #aaa;*/
  }
  .el-radio-button__inner {
    border-left: 1px solid #bfcbd9;
    margin-right: 10px;
    margin-bottom: 8px;
  }
  .el-radio-button--small .el-radio-button__inner {
    border-radius: 4px;
  }
  .el-radio__inner {
    border-radius: 20%;
  }
  .el-radio__inner::after{
    border-radius: 20%;
    background: #4d87df;
    width: 10px;
    height: 10px;
  }
  .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    background: rgba(53, 49, 55, 0.89);
    border-color: rgba(21, 17, 23, 0.89);
    box-shadow: -1px 0 0  rgba(21, 17, 23, 0.89)
  }
  .el-radio__input.is-checked .el-radio__inner {
    background: white;
    border-color: #4d87df;
  }
</style>
